package com.zzt.appframe8.widget;

import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatDrawableManager;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.DrawableUtils;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.google.android.material.R;

/**
 * @author: zeting
 * @date: 2022/9/1
 * 下方错误信息输入工具
 */
final class ErrorIndicatorController {
    private final Context context;
    private final MTextInputLayout textInputLayout;
    private LinearLayout bottomLayout; // 下方存放错误信息
    private CharSequence errorText;
    private boolean errorEnabled;
    private TextView errorView;
    private ColorStateList errorViewTextColor;// 字体颜色
    private float errorTextSize;// 字体大小

    private final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (before > 0 || count > 0) {
                hideError();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    public ErrorIndicatorController(@NonNull MTextInputLayout textInputView) {
        this.context = textInputView.getContext();
        this.textInputLayout = textInputView;
    }

    /**
     * 设置默认颜色
     */
    public void setErrorTextTintList(ColorStateList errorTintList) {
        if (errorTintList != null) {
            this.errorViewTextColor = errorTintList;
        }
        if (errorViewTextColor == null) {
            errorViewTextColor = ContextCompat.getColorStateList(context, R.color.design_error);
        }
        setErrorTextColor(errorViewTextColor);
    }

    /**
     * 设置字体大小
     */
    public void setErrorTextSize(float size) {
        errorTextSize = size;
        if (errorTextSize > 0) {
            if (errorView != null) {
                errorView.setTextSize(errorTextSize);
            }
        }
    }

    void setErrorEnabled(boolean enabled) {
        if (errorEnabled == enabled) {
            return;
        }
        if (enabled) {
            errorView = new AppCompatTextView(context);
            errorView.setId(R.id.textinput_error);
            if (Build.VERSION.SDK_INT >= 17) {
                errorView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
            }
            setErrorTextColor(errorViewTextColor);
            errorView.setVisibility(View.INVISIBLE);
            if (errorTextSize > 0) {
                errorView.setTextSize(errorTextSize);
            }
            addIndicator(errorView);
        } else {
            hideError();
            removeIndicator(errorView);
            errorView = null;
            updateEditTextBackground();
        }
        errorEnabled = enabled;
    }

    /**
     * 设置错误文本颜色
     *
     * @param errorViewTextColor
     */
    void setErrorTextColor(@Nullable ColorStateList errorViewTextColor) {
        this.errorViewTextColor = errorViewTextColor;
        if (errorView != null && errorViewTextColor != null) {
            errorView.setTextColor(errorViewTextColor);
        }
    }

    private boolean errorShouldBeShown() {
        return errorView != null && !TextUtils.isEmpty(errorText);
    }

    boolean isErrorEnabled() {
        return errorEnabled;
    }

    void showError(final CharSequence errorText) {
        this.errorText = errorText;
        errorView.setText(errorText);
        errorView.setVisibility(View.VISIBLE);
        updateEditTextBackground();
    }

    void hideError() {
        this.errorText = null;
        errorView.setText("");
        errorView.setVisibility(View.GONE);
        updateEditTextBackground();
    }

    @SuppressLint("RestrictedApi")
    void updateEditTextBackground() {
        // Only update the color filter for the legacy text field, since we can directly change the
        // Paint colors of the MaterialShapeDrawable box background without having to use color filters.
        LinearLayout editText = textInputLayout.getInputLayout();
        if (editText == null) {
            return;
        }

        Drawable editTextBackground = editText.getBackground();
        if (editTextBackground == null) {
            return;
        }

        if (DrawableUtils.canSafelyMutateDrawable(editTextBackground)) {
            editTextBackground = editTextBackground.mutate();
        }

        if (errorShouldBeShown()) {
            // Set a color filter for the error color
            editTextBackground.setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(getErrorViewCurrentTextColor(), PorterDuff.Mode.SRC_IN));
        } else {
            // Else reset the color filter and refresh the drawable state so that the
            // normal tint is used
            DrawableCompat.clearColorFilter(editTextBackground);
            editText.refreshDrawableState();
        }
    }

    /**
     * 添加错误信息布局
     *
     * @param indicator
     */
    void addIndicator(TextView indicator) {
        if (bottomLayout == null) {
            bottomLayout = new LinearLayout(context);
            bottomLayout.setOrientation(LinearLayout.HORIZONTAL);
            textInputLayout.addView(bottomLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        LinearLayout.LayoutParams indicatorAreaLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        bottomLayout.addView(indicator, indicatorAreaLp);
        bottomLayout.setVisibility(VISIBLE);
        EditText editText = textInputLayout.getEditText();
        if (editText != null) {
            editText.removeTextChangedListener(textWatcher);
            editText.addTextChangedListener(textWatcher);
        }
    }


    /**
     * 移除错误信息布局
     *
     * @param indicator
     */
    void removeIndicator(TextView indicator) {
        if (bottomLayout != null) {
            bottomLayout.removeView(indicator);
            bottomLayout.setVisibility(View.GONE);
        }
    }

    @ColorInt
    int getErrorViewCurrentTextColor() {
        return errorView != null ? errorView.getCurrentTextColor() : -1;
    }
}
